using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.Text.Json;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;

namespace Demo
{
    public partial class MainForm : Form
    {
        private List<TestData> dataList = new List<TestData>();
        private TestData? currentData;
        private bool isEditing = false;
        private string dataFilePath;

        public MainForm()
        {
            InitializeComponent();
            dataFilePath = Path.Combine(Application.StartupPath, "testdata.json");
            InitializeDataGridView();
            LoadData();
            UpdateLanguage();
            LanguageHelper.OnLanguageChanged += UpdateLanguage;
            UpdateUI();
        }
        
        private void InitializeDataGridView()
        {
            gridView.Columns.Clear();
            gridView.OptionsView.ColumnAutoWidth = false;

            void AddColumn(string fieldName, string caption, string? formatString = null, DevExpress.Utils.FormatType formatType = DevExpress.Utils.FormatType.None)
            {
                var column = gridView.Columns.AddField(fieldName);
                column.Caption = caption;
                column.Visible = true;
                column.OptionsColumn.AllowEdit = false;
                column.OptionsColumn.ReadOnly = true;
                if (!string.IsNullOrEmpty(formatString))
                {
                    column.DisplayFormat.FormatString = formatString;
                    column.DisplayFormat.FormatType = formatType;
                }
            }

            AddColumn("ParameterNumber", "参数编号");
            AddColumn("MainTesterName", "主试名字");
            AddColumn("ChildName", "儿童名字");
            AddColumn("TestDate", "测试日期", "yyyy-MM-dd", DevExpress.Utils.FormatType.DateTime);
            AddColumn("BirthDate", "出生日期", "yyyy-MM-dd", DevExpress.Utils.FormatType.DateTime);
            AddColumn("Grade", "所在年级");
            AddColumn("ParentEducation", "家长教育程度");
            AddColumn("PhoneNumber", "电话号码");
            AddColumn("VideoGame", "电子游戏");
            AddColumn("Address", "联系地址");
            AddColumn("Remarks", "备注资料");
            AddColumn("ChildGender", "儿童性别");
            AddColumn("HandPreference", "用手习惯");

            // 测试分数列
            AddColumn("Blocks", "积木", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("Comprehension", "常识", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("MatrixReasoning", "矩阵推理", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("BugSearch", "找虫", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("PictureMemory", "图片记忆", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("Similarities", "类同", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("PictureConcepts", "图书概念", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("Cancellation", "画消", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("AnimalHome", "动物家园", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("Puzzle", "拼图", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("AnimalCoding", "动物译码", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("Understanding", "理解", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("PictureRecognition", "指认图片", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("PictureNaming", "图片命名", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("RandomCancellation", "随机画消", "0.##", DevExpress.Utils.FormatType.Numeric);
            AddColumn("OrderedCancellation", "有序画消", "0.##", DevExpress.Utils.FormatType.Numeric);

            // 统计设置
            AddColumn("ConfidenceLevel", "信赖水平");
            AddColumn("StatisticalSignificance", "统计显著性水准");
            AddColumn("ComparisonBasis", "比较基础");
            AddColumn("CalculationMethod", "计算方法1");
            AddColumn("CalculationMethod2", "计算方法2");
        }

        private void UpdateLanguage()
        {
            // 更新界面文本
            this.Text = LanguageHelper.GetString("DataManagement");
            // 这里可以添加更多语言更新逻辑
            RefreshDataGridView();
        }

        private void LoadData()
        {
            try
            {
                if (File.Exists(dataFilePath))
                {
                    var json = File.ReadAllText(dataFilePath, Encoding.UTF8);
                    dataList = JsonSerializer.Deserialize<List<TestData>>(json) ?? new List<TestData>();
                }
            }
            catch { }
        }

        private void SaveData()
        {
            try
            {
                var json = JsonSerializer.Serialize(dataList, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(dataFilePath, json, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAdd_Click(object? sender, EventArgs e)
        {
            ClearForm();
            currentData = new TestData();
            isEditing = false;
            UpdateUI();
            txtParameterNumber.Focus();
        }

        private void btnEdit_Click(object? sender, EventArgs e)
        {
            if (gridView.FocusedRowHandle < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择要编辑的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var index = gridView.FocusedRowHandle;
            if (index >= 0 && index < dataList.Count)
            {
                currentData = dataList[index];
                LoadDataToForm(currentData);
                isEditing = true;
                UpdateUI();
            }
        }

        private void btnDelete_Click(object? sender, EventArgs e)
        {
            if (gridView.FocusedRowHandle < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择要删除的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (DevExpress.XtraEditors.XtraMessageBox.Show("确定要删除选中的记录吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var index = gridView.FocusedRowHandle;
                if (index >= 0 && index < dataList.Count)
                {
                    dataList.RemoveAt(index);
                    SaveData();
                    RefreshDataGridView();
                    ClearForm();
                    currentData = null;
                    isEditing = false;
                    UpdateUI();
                }
            }
        }

        private void btnSave_Click(object? sender, EventArgs e)
        {
            if (!ValidateForm())
                return;

            if (currentData == null)
                currentData = new TestData();

            SaveFormToData(currentData);

            if (!isEditing)
            {
                dataList.Add(currentData);
            }

            SaveData();
            RefreshDataGridView();
            DevExpress.XtraEditors.XtraMessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            ClearForm();
            currentData = null;
            isEditing = false;
            UpdateUI();
        }

        private void btnCancel_Click(object? sender, EventArgs e)
        {
            ClearForm();
            currentData = null;
            isEditing = false;
            UpdateUI();
        }

        private void btnReEnter_Click(object? sender, EventArgs e)
        {
            ClearForm();
            currentData = null;
            isEditing = false;
            UpdateUI();
            txtParameterNumber.Focus();
        }

        private void btnGenerateReport_Click(object? sender, EventArgs e)
        {
            if (currentData == null || string.IsNullOrWhiteSpace(currentData.ParameterNumber))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请先保存数据后再生成报告", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var password = txtReportPassword.Text;
            if (string.IsNullOrWhiteSpace(password))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请为报告添加密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtReportPassword.Focus();
                return;
            }

            var passwordHash = ComputeMD5(password);
            currentData.ReportPassword = passwordHash;

            SaveData();
            DevExpress.XtraEditors.XtraMessageBox.Show("报告密码已设置并保存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private bool ValidateForm()
        {
            if (string.IsNullOrWhiteSpace(txtParameterNumber.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请输入参数编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtParameterNumber.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtMainTesterName.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请输入主试名字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtMainTesterName.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtChildName.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请输入儿童名字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtChildName.Focus();
                return false;
            }

            return true;
        }

        private void SaveFormToData(TestData data)
        {
            data.ParameterNumber = txtParameterNumber.Text.Trim();
            data.MainTesterName = txtMainTesterName.Text.Trim();
            data.ChildName = txtChildName.Text.Trim();
            data.TestDate = dtpTestDate.DateTime;
            data.BirthDate = dtpBirthDate.DateTime;
            data.Grade = cmbGrade.EditValue?.ToString();
            data.ParentEducation = cmbParentEducation.EditValue?.ToString();
            data.PhoneNumber = txtPhoneNumber.Text.Trim();
            data.VideoGame = txtEmail.Text.Trim();
            data.Address = txtAddress.Text.Trim();
            data.Remarks = txtRemarks.Text.Trim();
            data.ChildGender = GetSelectedRadio(groupGender);
            data.HandPreference = GetSelectedRadio(groupHandPreference);

            // 测试分数
            data.Blocks = ParseDecimal(txtBlocks.Text);
            data.Comprehension = ParseDecimal(txtComprehension.Text);
            data.MatrixReasoning = ParseDecimal(txtMatrixReasoning.Text);
            data.BugSearch = ParseDecimal(txtBugSearch.Text);
            data.PictureMemory = ParseDecimal(txtPictureMemory.Text);
            data.Similarities = ParseDecimal(txtSimilarities.Text);
            data.PictureConcepts = ParseDecimal(txtPictureConcepts.Text);
            data.Cancellation = ParseDecimal(txtCancellation.Text);
            data.AnimalHome = ParseDecimal(txtAnimalHome.Text);
            data.Puzzle = ParseDecimal(txtPuzzle.Text);
            data.AnimalCoding = ParseDecimal(txtAnimalCoding.Text);
            data.Understanding = ParseDecimal(txtUnderstanding.Text);
            data.PictureRecognition = ParseDecimal(txtPictureRecognition.Text);
            data.PictureNaming = ParseDecimal(txtPictureNaming.Text);
            data.RandomCancellation = ParseDecimal(txtRandomCancellation.Text);
            data.OrderedCancellation = ParseDecimal(txtOrderedCancellation.Text);

            // 统计设置
            data.ConfidenceLevel = GetSelectedRadio(groupConfidenceLevel);
            data.StatisticalSignificance = GetSelectedRadio(groupStatisticalSignificance);
            data.ComparisonBasis = GetSelectedRadio(groupComparisonBasis);
            data.CalculationMethod = GetSelectedRadio(groupCalculationMethod);
            data.CalculationMethod2 = GetSelectedRadio(groupCalculationMethod2);
        }

        private void LoadDataToForm(TestData data)
        {
            txtParameterNumber.Text = data.ParameterNumber;
            txtMainTesterName.Text = data.MainTesterName;
            txtChildName.Text = data.ChildName;
            dtpTestDate.DateTime = data.TestDate;
            dtpBirthDate.DateTime = data.BirthDate;
            cmbGrade.EditValue = data.Grade;
            cmbParentEducation.EditValue = data.ParentEducation;
            txtPhoneNumber.Text = data.PhoneNumber ?? "";
            txtEmail.Text = data.VideoGame ?? "";
            txtAddress.Text = data.Address ?? "";
            txtRemarks.Text = data.Remarks ?? "";
            SetSelectedRadio(groupGender, data.ChildGender);
            SetSelectedRadio(groupHandPreference, data.HandPreference);

            txtBlocks.Text = data.Blocks?.ToString() ?? "";
            txtComprehension.Text = data.Comprehension?.ToString() ?? "";
            txtMatrixReasoning.Text = data.MatrixReasoning?.ToString() ?? "";
            txtBugSearch.Text = data.BugSearch?.ToString() ?? "";
            txtPictureMemory.Text = data.PictureMemory?.ToString() ?? "";
            txtSimilarities.Text = data.Similarities?.ToString() ?? "";
            txtPictureConcepts.Text = data.PictureConcepts?.ToString() ?? "";
            txtCancellation.Text = data.Cancellation?.ToString() ?? "";
            txtAnimalHome.Text = data.AnimalHome?.ToString() ?? "";
            txtPuzzle.Text = data.Puzzle?.ToString() ?? "";
            txtAnimalCoding.Text = data.AnimalCoding?.ToString() ?? "";
            txtUnderstanding.Text = data.Understanding?.ToString() ?? "";
            txtPictureRecognition.Text = data.PictureRecognition?.ToString() ?? "";
            txtPictureNaming.Text = data.PictureNaming?.ToString() ?? "";
            txtRandomCancellation.Text = data.RandomCancellation?.ToString() ?? "";
            txtOrderedCancellation.Text = data.OrderedCancellation?.ToString() ?? "";

            SetSelectedRadio(groupConfidenceLevel, data.ConfidenceLevel);
            SetSelectedRadio(groupStatisticalSignificance, data.StatisticalSignificance);
            SetSelectedRadio(groupComparisonBasis, data.ComparisonBasis);
            SetSelectedRadio(groupCalculationMethod, data.CalculationMethod);
            SetSelectedRadio(groupCalculationMethod2, data.CalculationMethod2);
        }

        private void ClearForm()
        {
            txtParameterNumber.Text = "";
            txtMainTesterName.Text = "";
            txtChildName.Text = "";
            dtpTestDate.DateTime = DateTime.Now;
            dtpBirthDate.DateTime = DateTime.Now;
            cmbGrade.EditValue = null;
            cmbParentEducation.EditValue = null;
            txtPhoneNumber.Text = "";
            txtEmail.Text = "";
            txtAddress.Text = "";
            txtRemarks.Text = "";
            SetSelectedRadio(groupGender, "男性");
            SetSelectedRadio(groupHandPreference, "右手");

            // 清空所有分数字段
            foreach (var txt in GetAllScoreTextBoxes())
            {
                txt.Text = "";
            }

            SetSelectedRadio(groupConfidenceLevel, "95%");
            SetSelectedRadio(groupStatisticalSignificance, "0.05");
            SetSelectedRadio(groupComparisonBasis, "全样本");
            SetSelectedRadio(groupCalculationMethod, "替代分检验");
            SetSelectedRadio(groupCalculationMethod2, "画消");
            txtReportPassword.Text = "";
        }

        private void RefreshDataGridView()
        {
            gridControl.DataSource = null;
            gridControl.DataSource = dataList;
            gridView.RefreshData();
            gridView.BestFitColumns();
        }

        private void UpdateUI()
        {
            bool hasData = currentData != null;
            btnSave.Enabled = hasData;
            btnCancel.Enabled = hasData;
            btnReEnter.Enabled = hasData;
        }

        private decimal? ParseDecimal(string text)
        {
            if (decimal.TryParse(text, out decimal result))
                return result;
            return null;
        }

        private string GetSelectedRadio(RadioGroup radioGroup)
        {
            if (radioGroup.SelectedIndex >= 0 && radioGroup.SelectedIndex < radioGroup.Properties.Items.Count)
            {
                return radioGroup.Properties.Items[radioGroup.SelectedIndex].Description;
            }
            return "";
        }

        private void SetSelectedRadio(RadioGroup radioGroup, string value)
        {
            for (int i = 0; i < radioGroup.Properties.Items.Count; i++)
            {
                if (radioGroup.Properties.Items[i].Description == value)
                {
                    radioGroup.SelectedIndex = i;
                    return;
                }
            }
        }

        private List<TextEdit> GetAllScoreTextBoxes()
        {
            return new List<TextEdit>
            {
                txtBlocks, txtComprehension, txtMatrixReasoning, txtBugSearch,
                txtPictureMemory, txtSimilarities, txtPictureConcepts, txtCancellation,
                txtAnimalHome, txtPuzzle, txtAnimalCoding, txtUnderstanding,
                txtPictureRecognition, txtPictureNaming, txtRandomCancellation, txtOrderedCancellation
            };
        }

        private static string ComputeMD5(string input)
        {
            using var md5 = MD5.Create();
            var bytes = Encoding.UTF8.GetBytes(input);
            var hash = md5.ComputeHash(bytes);
            return BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant();
        }

        private void dgvData_SelectionChanged(object? sender, EventArgs e)
        {
            if (sender is GridView view && view.FocusedRowHandle >= 0)
            {
                var index = view.FocusedRowHandle;
                if (index >= 0 && index < dataList.Count)
                {
                    currentData = dataList[index];
                    LoadDataToForm(currentData);
                    isEditing = true;
                    UpdateUI();
                }
            }
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            LanguageHelper.OnLanguageChanged -= UpdateLanguage;
            base.OnFormClosed(e);
        }
        
        private void MenuSkin_Click(object? sender, EventArgs e)
        {
            using (var form = new SkinSelectionForm())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    var selectedSkin = form.SelectedSkin;
                    if (!string.IsNullOrEmpty(selectedSkin))
                    {
                        try
                        {
                            SkinManager.SaveSkin(selectedSkin);
                            var message = $"皮肤已切换为: {selectedSkin}\n\n";
                            
                            // 检查是否是 Bonus Skin
                            if (SkinManager.BonusSkins.Contains(selectedSkin))
                            {
                                message += "✓ 此皮肤为外置皮肤（Bonus Skin）\n\n";
                            }
                            
                            message += "皮肤已应用到当前窗口。\n";
                            message += "如需应用到所有窗口，请重启应用程序。";
                            
                            XtraMessageBox.Show(message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            XtraMessageBox.Show($"无法应用皮肤: {ex.Message}\n\n可能原因：\n1. 该皮肤未安装\n2. 需要安装 DevExpress Bonus Skins 包", 
                                "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }
    }
}

